/*

 Copyright 2012 Peter Dornbach.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
   
*/

package com.dornbachs.zebra.guitarear;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SelectActivity extends BaseActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.select);
    
    _challenge = Challenge.getChallenge(this);
  	if (getIntent().getAction().equals(INTENT_SELECT_PRACTICE)) {
  		if (_currentLevel == null)
  			_currentLevel = new Level();
  		_isPractice = true;
  	} else {
  		if (_currentLevel == null)
  			_currentLevel = _challenge.getUserState().defaultBaseLevel();
  		_isPractice = false;
  	}

    _lessButtons = new Button[DIMENSIONS];
    _lessButtons[0] = (Button)findViewById(R.id.button_select_0_less);
    _lessButtons[1] = (Button)findViewById(R.id.button_select_1_less);
    _lessButtons[2] = (Button)findViewById(R.id.button_select_2_less);
    //_lessButtons[3] = (Button)findViewById(R.id.button_select_3_less);
    _lessButtons[4] = (Button)findViewById(R.id.button_select_4_less);

    _moreButtons = new Button[DIMENSIONS];
    _moreButtons[0] = (Button)findViewById(R.id.button_select_0_more);
    _moreButtons[1] = (Button)findViewById(R.id.button_select_1_more);
    _moreButtons[2] = (Button)findViewById(R.id.button_select_2_more);
    //_moreButtons[3] = (Button)findViewById(R.id.button_select_3_more);
    _moreButtons[4] = (Button)findViewById(R.id.button_select_4_more);
    
    _levelTexts = new TextView[DIMENSIONS];
    _levelTexts[0] = (TextView)findViewById(R.id.textView_select_0);
    _levelTexts[1] = (TextView)findViewById(R.id.textView_select_1);
    _levelTexts[2] = (TextView)findViewById(R.id.textView_select_2);
    //_levelTexts[3] = (TextView)findViewById(R.id.textView_select_3);
    _levelTexts[4] = (TextView)findViewById(R.id.textView_select_4);

    _levelStrings = new String[DIMENSIONS][];
    _levelStrings[0] = getResources().getStringArray(R.array.text_select_0_values);
    _levelStrings[1] = getResources().getStringArray(R.array.text_select_1_values);
    _levelStrings[2] = getResources().getStringArray(R.array.text_select_2_values);
    //_levelStrings[3] = getResources().getStringArray(R.array.text_select_3_values);
    _levelStrings[4] = getResources().getStringArray(R.array.text_select_4_values);
    
    for (int i = 0; i < DIMENSIONS; ++i) {
    	if (_lessButtons[i] != null) {
    		_lessButtons[i].setOnClickListener(new LevelAdjuster(i, -1));
    		_moreButtons[i].setOnClickListener(new LevelAdjuster(i, +1));
    	}
    }

    _practiceButton = (Button)findViewById(R.id.button_select_multi);
    if (_isPractice) {
    	_practiceButton.setText(R.string.button_select_practice);
      _practiceButton.setOnClickListener(
      		new View.OnClickListener() {
      			public void onClick(View view) {
      				_challenge.tryPractice(_currentLevel);
      				startActivity(new Intent(INTENT_PRACTICE));
      			}
      		});
    } else {
    	_practiceButton.setText(R.string.button_select_score);
      _practiceButton.setOnClickListener(
      		new View.OnClickListener() {
      			public void onClick(View view) {
      				showDialog(DIALOG_SCORE_ID);
      			}
      		});
    }
    findViewById(R.id.button_select_back).setOnClickListener(
    		new View.OnClickListener() {
    			public void onClick(View view) {
    				finish();
    			}
    		});

    if (savedInstanceState != null) {
    	_currentLevel = Level.fromString(savedInstanceState.get(KEY_CURRENTLEVEL).toString());
    }
		updateViewState();
  }

  @Override
  public void onPause() {
  	// Save instance state.
  	_challenge.getUserState().save(this);
  	super.onPause();
  }
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  	// When PracticeActivity finishes, it may update what
  	// levels are available, reflect that here.
  	updateViewState();
  }
  
  @Override
  protected void onSaveInstanceState(Bundle savedInstanceState) {
  	savedInstanceState.putString(KEY_CURRENTLEVEL, _currentLevel.toString());
  	super.onSaveInstanceState(savedInstanceState);
  }

	@Override
	protected Dialog onCreateDialog(int id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    switch(id) {
    case DIALOG_SCORE_ID:
    	dialog.setButton(
    			AlertDialog.BUTTON_NEGATIVE,
    			getString(R.string.button_score_reset),
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
              showDialog(DIALOG_SCORE_RESET_CONFIRM_ID);
              dialog.dismiss();
            }
          });
    	dialog.setButton(
    			AlertDialog.BUTTON_POSITIVE,
    			getString(R.string.button_ok),
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	 dialog.dismiss();
            }
          });
    	prepareDialog(dialog);
    	return dialog;
    case DIALOG_SCORE_RESET_CONFIRM_ID:
    	dialog.setMessage(getString(R.string.text_score_reset_confirm));
    	dialog.setButton(
					AlertDialog.BUTTON_NEGATIVE,
					getString(R.string.button_back),
		      new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		        	 dialog.dismiss();
		        }
		      });
    	dialog.setButton(
    			AlertDialog.BUTTON_POSITIVE,
    			getString(R.string.button_score_reset),
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	_challenge.getUserState().resetScore();
            	_currentLevel = new Level();
            	updateViewState();
            	dialog.dismiss();
            }
          });
    	return dialog;
    default:
    	return super.onCreateDialog(id);
    }
  }

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
    switch(id) {
    case DIALOG_SCORE_ID:
    	prepareDialog((AlertDialog)dialog);
			break;
		}
	}
	
	protected void prepareDialog(AlertDialog dialog) {
  	dialog.setMessage(
  			getString(R.string.text_score,
  			_challenge.getUserState().score()));
	}


  private void updateViewState() {
  	if (_isPractice) {
     	for (int i = 0; i < _lessButtons.length; ++i) {
     		if (_lessButtons[i] != null) {
       		_lessButtons[i].setEnabled(_currentLevel.get(i) > 0);
       		_moreButtons[i].setEnabled(_currentLevel.canGrow(i));
       		_moreButtons[i].setText(R.string.button_select_more);
       		_moreButtons[i].setTag(null);
       		_levelTexts[i].setText(_levelStrings[i][_currentLevel.get(i)]);
     		}
    	}
     	_practiceButton.setEnabled(_currentLevel.isAllowed());
  	} else {
     	for (int i = 0; i < _lessButtons.length; ++i) {
     		if (_lessButtons[i] != null) {
     			_lessButtons[i].setEnabled(_currentLevel.get(i) > 0);
     			_moreButtons[i].setEnabled(_currentLevel.canGrow(i));
     			if (_challenge.getUserState().needsImprove(_currentLevel, i)) {
     				_moreButtons[i].setText(R.string.button_select_improve);
     				_moreButtons[i].setTag(TAG_LAUNCH_PRACTICE);
     			} else {
     				_moreButtons[i].setText(R.string.button_select_more);
     				_moreButtons[i].setTag(null);
     			}
     			_levelTexts[i].setText(_levelStrings[i][_currentLevel.get(i)]);
     		}
    	}
  	}
  }
  
  private class LevelAdjuster implements View.OnClickListener {
  	public LevelAdjuster(int idx, int add) {
  		_idx = idx;
  		_add = add;
  	}
  	
		public void onClick(View view) {
			if (view.getTag() == null) {
				// No tag -> only adjust, do not launch PracticeActivity.
				_currentLevel.set(_idx, _currentLevel.get(_idx) + _add);
				if (_add > 0 && !_isPractice) {
					// If we are not practicing then it is possible that increasing one
					// thing decreases others.
					_challenge.getUserState().trimLevel(_currentLevel, _idx);
				}
				updateViewState();
			} else {
				// A button is tagged iff pressing it launches PracticeActiviy.
				Level tryLevel = _currentLevel.clone();
				tryLevel.set(_idx, tryLevel.get(_idx) + _add);
				_challenge.tryImprove(tryLevel);
				startActivityForResult(new Intent(INTENT_PRACTICE), REQUEST_DEFAULT);
			}
		}
		
  	private int _idx;
  	private int _add;
  };
  
  private static final int DIALOG_SCORE_ID = 1;
  private static final int DIALOG_SCORE_RESET_CONFIRM_ID = 2;
  
  private static final int DIMENSIONS = Level.DIMENSIONS;
  
  private static final Object TAG_LAUNCH_PRACTICE = new Object();
  private static final String KEY_CURRENTLEVEL = "CURRENT_LEVEL";

  Button[] _lessButtons;
  Button[] _moreButtons;
  TextView[] _levelTexts;
  String[][] _levelStrings;
  Button _practiceButton;
  
  Challenge _challenge;
  Level _currentLevel;
  boolean _isPractice;
}